import axios from 'axios'
import { Modal } from 'antd'

/**
 * 异步请求接口封装
 */
class AxiosUtils {

    // GET请求
    static ajax(options) {
        // 加载loading
        let loading;
        if (options.data && options.data.isShowLoading !== false){
            loading = document.getElementById('ajaxLoading');
            loading.style.display = 'block';
        }

        console.log("GET请求参数为==>", options)
        
        // 返回一个Promise对象
        return new Promise((resolve, reject) => {
            axios({
                url: options.url,
                method: options.method,
                timeout: 3000,
                params: (options.data && options.data.params) || "",
                headers: options.headers || {}
            }).then(response => {
                // 结束loading
                if (options.data && options.data.isShowLoading !== false) {
                    loading = document.getElementById('ajaxLoading');
                    loading.style.display = 'none';
                }
                
                if(response.status == '200') {
                    let res = response.data
                    if(res.code === 0) {
                        resolve(res)
                    }else{
                        Modal.warn({
                            title: '提示',
                            content: res.msg
                        })
                    } 
                }else{
                    reject(response.data)
                }
            })
        })
    }

    // POST请求，也适用于 PUT 和 PATCH
    static ajaxPost(options) {
        // 加载loading
        let loading;
        if (options.data && options.data.isShowLoading !== false){
            loading = document.getElementById('ajaxLoading');
            loading.style.display = 'block';
        }
        
        console.log("POST请求参数为==>", options)

        // 返回一个Promise对象
        return new Promise((resolve, reject) => {
            axios({
                url: options.url,
                method: options.method,
                timeout: 3000,
                data: (options.data && options.data.params) || "",
                headers: options.headers || {}
            }).then(response => {
                // 结束loading
                if (options.data && options.data.isShowLoading !== false) {
                    loading = document.getElementById('ajaxLoading');
                    loading.style.display = 'none';
                }
                
                if(response.status == '200') {
                    let res = response.data
                    if(res.code === 0) {
                        resolve(res)
                    }else{
                        Modal.info({
                            title: '提示',
                            content: res.msg
                        })
                    } 
                }else{
                    reject(response.data)
                }
            })
        })
    }
}

export default AxiosUtils